<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <!-- card body -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="一级分类">
        <!-- 通过 v-model 双向绑定小菠萝中的数据（pinia 中的数据可以直接修改） -->
        <el-select
          placeholder="请选择"
          v-model="(category1Id as number)"
          @change="handleCartgoryOne"
        >
          <el-option
            v-for="item in categoryList1"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select
          placeholder="请选择"
          v-model="(category2Id as number)"
          @change="handleCartgoryTwo"
        >
          <el-option
            v-for="item in categoryList2"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select placeholder="请选择" v-model="(category3Id as number)">
          <el-option
            v-for="item in categoryList3"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Cartgory",
});
</script>

<script setup lang="ts">
import { onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useCartgoryStore } from "@/stores/cartgory";
import { storeToRefs } from "pinia";

/* 一级分类 */
const cartgoryStore = useCartgoryStore();
const {
  categoryList1,
  category1Id,
  categoryList2,
  category2Id,
  categoryList3,
  category3Id,
} = storeToRefs(cartgoryStore);
const { categoryOneAction, categoryTwoAction, categoryThreeAction } =
  cartgoryStore;
// 获取一级分类数据
const getcategoryOne = async () => {
  try {
    await categoryOneAction();
  } catch (error) {
    ElMessage.error("一级分类请求失败！！！");
  }
};
// 选中一级分类事件(请求二级分类数据)
const handleCartgoryOne = async () => {
  // 清空二、三级分类可能残留的数据
  categoryList2.value = [];
  categoryList3.value = [];
  category2Id.value = null;
  category3Id.value = null;
  try {
    await categoryTwoAction();
  } catch (error) {
    ElMessage.error("二级分类请求失败！！！");
  }
};
// 选中二级分类事件(请求三级分类数据)
const handleCartgoryTwo = async () => {
  // 清空三级分类可能残留的书
  categoryList3.value = [];
  category3Id.value = null;
  try {
    await categoryThreeAction();
  } catch (error) {
    ElMessage.error("三级分类请求失败！！！");
  }
};
// 页面初始操作
onMounted(() => {
  getcategoryOne();
});
</script>
